<template>
  <div class="rightBodyContent">
    <div class="rightBodyContent-in">
      <div class="mb-10">
        <el-input v-model="materielName" size="small" placeholder="物料名称" class="w-200"></el-input>
        <el-date-picker
          v-model="value1"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          size="small"
          class="mr-10"
          :picker-options="pickerOptions1">
        </el-date-picker>
        <downexcel type="MaterialInHistory" :disabled="value1 && value1.length>0?false:true"
                   :option="{start_time:value1&&value1[0]?value1[0]:'',end_time:value1&&value1[1]?value1[1]:'',name:materielName}"
                   :excelName="`${value1&&value1[0]?value1[0]:''}至${value1&&value1[1]?value1[1]:''}${materielName}`"></downexcel>
      </div>
      <div class="mb-10">
        <el-input v-model="editForm.name" placeholder="物料名称" size="small" class="w-200 mr-10"></el-input>
        <el-select v-model="editForm.warehouse_id" placeholder="请选择仓库" size="small" class="w-140 mr-10">
          <el-option
            v-for="item in warehouseList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
        <el-select v-model="editForm.type" placeholder="已报警的物料" size="small"
                   class="w-140 mr-10">
          <el-option :label="item.name" :value="item.id" v-for="(item, index) in typeList"
                     :key="index"></el-option>
        </el-select>
        <el-button type="primary" size="small" @click="searchFn"><i class="el-icon-search"></i>搜索</el-button>
        <el-button size="small" @click="refreshFn"><i class="el-icon-refresh"></i>重置刷新</el-button>
      </div>
      <div class="toplineBox mb-10">
        <div class="toplineBox-left">
          <el-button type="primary" size="small" @click.native="addBook(1)">添加物料</el-button>
          <el-button type="danger" size="small" :disabled="handleSelection.length==0?true:false"
                     @click="handleDetel(2)">
            批量删除
          </el-button>
          <el-upload
            :action="$uploadImg"
            :on-success="handleSuccess"
            :on-progress="handleProgress"
            :show-file-list="false"
            accept=".xls,.xlsx"
            class="el-upload-body mr-10 ml-10">
            <el-button size="small">导入物料</el-button>
          </el-upload>
          <!--          <download type="Material" :option="{phone:editForm.phone}"></download>-->
          <downexcel type="Material" :option="{warehouse_id: editForm.warehouse_id}"></downexcel>
          <el-button size="small" @click="rankingVisible=true">物料使用排行榜</el-button>
          <el-button size="small" plain type="primary" @click="applyVisible=true">采购单入库</el-button>
        </div>
        <p class="numberline toplineBox-right">总{{ page.total }}条</p>
      </div>
      <!--本体列表，数据 -->
      <div class="table-body">
        <div class="table-body-box">
          <el-table
            ref="multipleTable"
            :data="arryList"
            :stripe="tableStripe"
            :border="tableBorder"
            tooltip-effect="dark"
            style="width: 100%"
            header-cell-class-name="table-text-c"
            cell-class-name="table-text-c"
            @selection-change="handleSelectionChange">
            <el-table-column
              type="selection"
              width="50"
              align="center">
            </el-table-column>
            <el-table-column
              prop="name"
              label="物料名称">
            </el-table-column>
            <el-table-column
              label="库存/单位"
              width="140">
              <template slot-scope="scope">
                {{ scope.row.number }} / {{ scope.row.unit }}
              </template>
            </el-table-column>
            <el-table-column
              label="警报数量"
              width="180">
              <template slot-scope="scope">
                <span :class="scope.row.number<scope.row.warming?'c-danger':''">{{ scope.row.warming }}</span>
              </template>
            </el-table-column>
            <!--            <el-table-column-->
            <!--                prop="unit"-->
            <!--                label="单位"-->
            <!--                width="100">-->
            <!--            </el-table-column>-->
            <el-table-column
              prop="phone"
              label="仓库">
              <template slot-scope="scope">
                {{ scope.row.warehouse ? scope.row.warehouse.name : '--' }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="160">
              <template slot-scope="scope">
                <el-dropdown @command="handleCommand" trigger="click">
                  <el-button type="primary" size="mini">
                    更多操作<i class="el-icon-arrow-down el-icon--right"></i>
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item :command="1+'-'+scope.$index">物料入库</el-dropdown-item>
                    <el-dropdown-item :command="2+'-'+scope.$index">入库记录</el-dropdown-item>
                    <el-dropdown-item :command="3+'-'+scope.$index">消耗记录</el-dropdown-item>
                    <el-dropdown-item :command="4+'-'+scope.$index">编辑物料</el-dropdown-item>
                    <el-dropdown-item :command="5+'-'+scope.$index">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <!--工具条-->
      <el-col :span="24" class="toolbar">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :total="page.total"
          :page-size="page.pagesize"
          :current-page="page.pageindex"
          @current-change="handleSizeChange">
        </el-pagination>
      </el-col>
    </div>
    <MaterRankingModle :visible.sync="rankingVisible"></MaterRankingModle>
    <!--    入库记录-->
    <WarehousingRecord :visible.sync="wareVisible" :materielOption="materielOption"></WarehousingRecord>
    <!--    消耗记录-->
    <ConsumptionRecord :visible.sync="consumpVisible" :materielOption="materielOption"></ConsumptionRecord>
    <!--    编辑添加物料-->
    <detailPage :visible.sync="detailVisible" :materielOption="materielOption" @InitFn="InitFn"></detailPage>
    <!--    采购单入库 applytype 2 物料 3 教具-->
    <Po_receipt :visible.sync="applyVisible" applytype="2" @InitFn="InitFn"></Po_receipt>
  </div>
</template>

<script>
import {pagination} from '@/utils/util.js'
import api from '@/utils/api.js'
import detailPage from "./manage/detail";
import WarehousingRecord from "./manage/WarehousingRecord";
import ConsumptionRecord from "./manage/ConsumptionRecord";
import Po_receipt from "./Po_receipt";

export default {
  components: {
    WarehousingRecord,
    ConsumptionRecord,
    detailPage,
    Po_receipt
  },
  data() {
    return {
      value1: [],
      pickerOptions1: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      },
      materielName: '',
      applyVisible: false,
      wareVisible: false, // 入库记录
      consumpVisible: false, // 消耗记录
      detailVisible: false, // 编辑详情
      materielOption: null, // 物料信息
      handleSelection: [],
      rankingVisible: false, // 排行
      tableStripe: true, // 是否斑马栏
      tableBorder: true, // 单元格右边边框
      editForm: {
        name: '',
        type: '',
        p: '', //
        warehouse_id: ''
      }, // 编辑界面数据
      page: {
        pageindex: pagination.pageIndex,
        pagesize: pagination.pageSize,
        total: pagination.total
      },
      arryList: [], // 数据列表
      warehouseList: [],
      typeList: [{name: '全部', id: ''}, {name: '未报警', id: 1}, {name: '已报警', id: 2}] //  	1未报警2已报警
    }
  },
  created() {
    this.InitFn()
    this.getWarehouse()
  },
  methods: {
    getWarehouse() {
      this.$fetch(this.api.mater.warehouse.index, {
        p: 1
      }).then((response) => {
        if (response.code === 0) {
          this.warehouseList = response.list.data
        } else {
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    // 初始化
    InitFn() {
      this.editForm.p = this.page.pageindex
      this.$fetch(api.admin_materiel_index, this.editForm).then((response) => {
        if (response.code === 0) {
          this.arryList = response.list.data
          this.page.total = response.list.total
        } else {
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    handleSelectionChange(val) {
      console.log('选择框选择变化', val) // 所有选中值
      this.handleSelection = val
    },
    searchFn() {
      this.page.pageindex = 1
      this.InitFn()
    },
    // 刷新页面
    refreshFn() {
      this.editForm.warehouse_id
      this.editForm.name = ''
      this.editForm.type = ''
      this.page.pageindex = 1
      this.InitFn()
    },
    // 提交数据
    editSubmit() {
      // 验证信息
      let _self = this
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          _self.submitBook()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 添加物料
    addBook(type, index) {
      this.materielOption = '';
      if (type === 2) {
        this.materielOption = this.arryList[index];
      }
      // this.$router.push('materieldetail?id=' + qurty)
      this.detailVisible = true;
    },
    // 提交新增，编辑书籍
    submitBook() {
      // 判断新增 编辑
      let _self = this
      let url_ = 'wuliao/add'
      let message = '添加成功'
      // 判断 tieleName添加，编辑
      // book/edit/id/707
      if (this.tieleName === '编辑') {
        url_ = 'wuliao/edit/id/' + this.editForm.id
        message = '编辑成功'
      }
      this.$post(url_, this.editForm).then((response) => {
        console.log(response)
        if (response.code === 0) {
          if (_self.page === 1) {
            _self.InitFn()
          }
          if (this.tieleName === '编辑') {
            _self.InitFn()
          }
          _self.$message({
            message: message,
            type: 'success'
          })
          _self.editFormVisible = false
          _self.$refs['editForm'].resetFields()
        } else {
          console.log('请求失败')
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    addNumber(index) {
      let title = '物料：' + this.arryList[index].name + ';请输入入库数量。'
      let that = this
      this.$prompt(title, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /[\d]{1,10}/,
        inputErrorMessage: '入库格式不正确（数字）'
      }).then(({value}) => {
        that.addmateriel(index, value)
      }).catch(() => {
      })
    },
    addmateriel(index, value) {
      this.$post(api.admin_materiel_log_purchase, {
        materiel_id: this.arryList[index].id,
        number: value
      }).then((response) => {
        if (response.code === 0) {
          this.InitFn()
          this.$message({
            type: 'success',
            message: '添加成功！ '
          })
        } else {
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    handleProgress() {
      this.progressPercent = parseInt(event.percent)
    },
    handleSuccess(response) {
      this.materielImport(response.data.name)
    },
    // 导入物料
    async materielImport(path) {
      let data = await this.$post(api.materiel_import, {file: path})
      if (data.code === 0) {
        this.$message({
          type: 'success',
          message: '导入成功!'
        })
        this.InitFn()
      }
    },
    beforeAvatarUpload(file) {
      console.log('上传数据excel：', file)
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      let status = 0
      for (let i in fileType['excel']) {
        if (fileType['excel'][i] === file.type) {
          status = 1
        }
      }
      if (!status) {
        this.$message.error('请上传相应的Excel文件')
        return false
      }
      return isLt2M
    },
    // 分页
    handleSizeChange(val) {
      this.page.pageindex = val
      this.arryList = []
      this.InitFn()
    },
    handleDetel(type, index) {
      this.$confirm('确认永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.detelRespon(type, index)
      }).catch(() => {
      })
    },
    detelRespon(type, index) {
      let option_ = []
      let data_ = {}
      if (type === 2) {
        for (let i in this.handleSelection) {
          option_.push(this.handleSelection[i].id)
        }
        data_.id = option_.join(',')
      } else {
        data_.id = this.arryList[index].id
      }
      console.log('删除得物料：', data_)
      this.$post(api.mater.listdelete, data_).then((response) => {
        if (response.code === 0) {
          this.InitFn()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        } else {
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    handleCommand(command) {
      let command_ = command.split('-')
      let n = this;
      if (Number(command_[0]) === 1) {
        this.addNumber(command_[1])
      }
      // 入库记录
      if (Number(command_[0]) === 2) {
        this.wareVisible = true // 入库记录
        this.materielOption = this.arryList[command_[1]]// 物料信息
      }
      // 消耗记录
      if (Number(command_[0]) === 3) {
        this.consumpVisible = true;
        this.materielOption = this.arryList[command_[1]];// 物料信息
      }
      if (Number(command_[0]) === 4) {
        this.addBook(2, command_[1])
      }
      if (Number(command_[0]) === 5) {
        this.handleDetel(1, command_[1])
      }
    }
  },
  mounted() {
  }
}
</script>

